package com.ljk.study5ormmybatis.service.impl;

import com.ljk.study5ormmybatis.entity.User;
import com.ljk.study5ormmybatis.exception.DataException;
import com.ljk.study5ormmybatis.mapper.UserMapper;
import com.ljk.study5ormmybatis.service.UserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * desc:
 *
 * @author ljk
 * @date 2021/3/25 8:56
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Override
    public List<User> findAllUser(){
        return userMapper.selectAllUser();
    }

    @Override
    public User findUserById(Long id) throws DataException {
        User user = userMapper.selectUserById(1L);
        if (user==null){
            throw new DataException(String.format("根据id[%s]没有找到对应的user数据",id));
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = DataException.class)
    public int updateUserPhoneById(Long id,String number) throws DataException {
        int i = userMapper.updatePhoneById(id, number);
        if (1==1){
            throw new DataException("测试事务");
        }
        return i;
    }

    @Override
    public String testTransactional() throws DataException {
        List<User> allUser = this.findAllUser();
        if (allUser.size()==0){
           throw new DataException("没有用户先建个用户再测试吧");
        }
        User userTemp = allUser.get(0);

        try {
            String rand = String.valueOf(new Random().nextInt(1000000));
        userService.updateUserPhoneById(userTemp.getId(),rand);
        } catch (DataException e) {
            System.err.println(e.getMessage());
        }
        User user = this.findUserById(userTemp.getId());
        return String.format("改之前[%s],改之后[%s]",userTemp.getPhoneNumber(),user.getPhoneNumber());
    }


}
